package com.hitalkie.teacher.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hitalkie.teacher.R;
import com.hitalkie.teacher.app.TalkieApi;
import com.hitalkie.teacher.fragment.LoadingDialogFragment;
import com.hitalkie.teacher.model.BaseResponse;
import com.hitalkie.teacher.util.OkHttpManager;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Date 06/11/2016
 *
 * @author charliema
 */

public class PhoneEditActivity extends BaseActivity{


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();

    }

    private void initView() {
        setContentView(R.layout.view_phone_edit);
        initTitleBar();

        initForm();
    }

    private void initTitleBar() {
        findViewById(R.id.viewTitleBarLeft).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
    }

    private void initForm() {
        findViewById(R.id.tvPhoneRegionCode).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        findViewById(R.id.tvSmsCodeRequest).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                smsCodeRequest();
            }
        });
        findViewById(R.id.tvConfirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phoneEdit();
            }
        });
    }

    private void smsCodeRequest() {
        EditText etPhone = (EditText) findViewById(R.id.etPhone);
        String phone = etPhone.getText().toString();
        if(TextUtils.isEmpty(phone)){
            etPhone.setError("不能为空");
            return;
        }
        smsCodeRequest(phone);
    }

    private void smsCodeRequest(String phone){
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");

        // assemble data
        Map<String, String> data = new HashMap<>();
        data.put("phone", phone);
        data.put("usage", "reset");

        OkHttpManager.client.newCall(
                new Request.Builder().url(TalkieApi.getHost() + TalkieApi.PATH_REQUEST_SMS_CODE)
                        //
                        .post(RequestBody.create(OkHttpManager.JSON, new Gson().toJson(data)))
                        .build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                // loading dialog
                                loadingDialogFragment.dismiss();
                                Toast.makeText(getActivity(), getText(R.string.network_exception), Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();
                        Log.e(TAG, "requestSmsCode  resp:" + jsonStr);

                        try {
                            final BaseResponse resp = new Gson().fromJson(jsonStr, BaseResponse.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {

                                    if (resp.status.error_code == 0) {
                                        onSmsCodeRequestSuccess(resp);
                                    } else {
                                        Toast.makeText(getActivity(), resp.status.error_message, Toast.LENGTH_LONG).show();
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            // loading dialog
                            loadingDialogFragment.dismiss();
                        }
                    }
                });
    }

    private void onSmsCodeRequestSuccess(BaseResponse resp) {
        // 倒计时 和 可用状态
        final TextView tv = (TextView) findViewById(R.id.tvSmsCodeRequest);
        tv.setEnabled(false);
        new CountDownTimer(20000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tv.setText("" + (millisUntilFinished / 1000) + " seconds remaining");
            }

            @Override
            public void onFinish() {
                tv.setText("request sms code");
                tv.setEnabled(true);
            }
        }.start();

    }

    private void phoneEdit() {
        EditText etPhone = (EditText) findViewById(R.id.etPhone);
        EditText etSmsCode = (EditText) findViewById(R.id.etSmsCode);
        TextView tvRegionCode = (TextView) findViewById(R.id.tvPhoneRegionCode);

        String phone = etPhone.getText().toString();
        String smsCode = etSmsCode.getText().toString();
        String regionCode = tvRegionCode.getText().toString();

        if(TextUtils.isEmpty(phone)){
            etPhone.setError("不能为空");
            return;
        }
        if(TextUtils.isEmpty(smsCode)){
            etSmsCode.setError("不能为空");
            return;
        }
        phoneEdit(regionCode+phone, smsCode);

    }

    private void phoneEdit(String phone, String smsCode){
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");

        // assemble data
        Map<String, String> data = new HashMap<>();
        data.put("phone", phone);
        data.put("code", smsCode);

        OkHttpManager.client.newCall(
                new Request.Builder().url(TalkieApi.getHost() + TalkieApi.PATH_PHONE)
                        //
                        .post(RequestBody.create(OkHttpManager.JSON, new Gson().toJson(data)))
                        .build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                // loading dialog
                                loadingDialogFragment.dismiss();
                                Toast.makeText(getActivity(), getText(R.string.network_exception), Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();
                        Log.e(TAG, "requestSmsCode  resp:" + jsonStr);

                        try {
                            final BaseResponse resp = new Gson().fromJson(jsonStr, BaseResponse.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {

                                    if (resp.status.error_code == 0) {
                                        Toast.makeText(getActivity(),"修改成功",Toast.LENGTH_LONG).show();
                                        Intent i = new Intent(getActivity(), MainActivity.class);
                                        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                        startActivity(i);
                                    } else {
                                        Toast.makeText(getActivity(), resp.status.error_message, Toast.LENGTH_LONG).show();
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            // loading dialog
                            loadingDialogFragment.dismiss();
                        }
                    }
                });
    }


}
